package com.hxzy.tms.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.util.WebUtils;

import com.hxzy.tms.SessionHolder;
import com.hxzy.tms.aciton.LoginAction;
import com.hxzy.tms.entity.User;
import com.hxzy.tms.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -8598742796549307651L;
    private UserService userService;

    @Override
    public void init() {
        super.init();
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();

        String actionResult = null;

        // 从线程上下文李取一次
        User session = SessionHolder.get();

        // 从会话里拿一次
        if (session == null) {
            session = (User) ActionContext.getContext().getSession().get(LoginAction.SESSION_KEY);
        }

        // 从 cookie 里拿
        if (session == null) {
            String hash = WebUtils.getCookie(request, "hash") != null ? WebUtils.getCookie(request, "hash").getValue()
                    : null;
            session = userService.getUser(hash, request.getRemoteAddr()).data;
        }

        if (session != null)
            SessionHolder.set(session);

        try {
            actionResult = invocation.invoke();
        } finally {
            // 用完了清除，防止该线程被其他请求复用导致获取到其他用户的会话信息
            SessionHolder.clear();
        }

        return actionResult;
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
